<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      
      <view class="navbar-title">我的收藏</view>
      <view class="navbar-right"></view>
    </view>

    <!-- 主内容区 -->
    <scroll-view class="content-scroll" scroll-y>
      <view class="module module-3">
        <view class="hot-articles">
          <view class="hot-title">收藏的文章</view>
          
          <!-- 无收藏时显示 -->
          <view class="empty-placeholder" v-if="collectedArticles.length === 0">
            您当前还没有收藏文章
          </view>
          
          <!-- 收藏文章列表 -->
          <view v-else class="articles-list">
            <view class="article-item" v-for="(item, index) in collectedArticles" :key="item.id" @click="goToArticle(item.pcurl)">
              <image :src="item.picture" class="article-img" mode="aspectFill"></image>
              <view class="article-content">
                <text class="article-title">{{ item.name }}</text>
                <text class="article-desc">{{ item.description }}</text>
              </view>
              <!-- 固定显示实心红心 -->
              <image 
                class="like-icon" 
                src="/static/red-heart.png"
                @click.stop="handleCancelLike(item)"
                mode="widthFix"
              ></image>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import config from '../../config.js';

export default {
  data() {
    return {
      collectedArticles: [] // 存储用户收藏的文章列表
    };
  },
  onLoad() {
    this.fetchCollectedArticles(); // 页面加载时获取收藏列表
  },
  onShow() {
    // 页面显示时刷新列表（确保取消收藏后及时更新）
    this.fetchCollectedArticles();
  },
  methods: {
    /**
     * 返回上一页
     */
    navigateBack() {
      uni.navigateBack({ delta: 1 });
    },

    /**
     * 获取用户收藏的文章列表
     */
    async fetchCollectedArticles() {
      const hospitalNumber = uni.getStorageSync('hospitalNumber');
      if (!hospitalNumber) {
        uni.showToast({ title: '未获取到医院编号', icon: 'none' });
        return;
      }
      try {
        const res = await uni.request({
          url: `${config.baseUrl}/patient/getUserLike`,
          method: 'POST',
          header: {
            'Authorization': uni.getStorageSync('token') || '',
            'Content-Type': 'application/json'
          },
          data: { hospitalNumber }
        });
        if (res.statusCode === 200 && res.data.code === 1) {
          this.collectedArticles = res.data.data || [];
        } else {
          uni.showToast({ title: '获取收藏文章失败', icon: 'none' });
        }
      } catch (error) {
        console.error('获取收藏文章出错:', error);
        uni.showToast({ title: '获取收藏文章失败', icon: 'none' });
      }
    },

    /**
     * 跳转到文章详情
     */
    goToArticle(url) {
      if (!url) {
        uni.showToast({ title: '文章链接不存在', icon: 'none' });
        return;
      }
      uni.navigateTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(url)}`
      });
    },

    /**
     * 取消收藏
     */
    handleCancelLike(item) {
      const hospitalNumber = uni.getStorageSync('hospitalNumber');
      uni.showModal({
        title: '提示',
        content: '您确定取消收藏这篇文章吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await uni.request({
                url: `${config.baseUrl}/patient/deleteLike`,
                method: 'POST',
                header: {
                  'Authorization': uni.getStorageSync('token') || '',
                  'Content-Type': 'application/json'
                },
                data: {
                  hospitalNumber,
                  hotArticleId: item.id
                }
              });
              if (response.statusCode === 200 && response.data.code === 1) {
                uni.showToast({ title: '取消收藏成功', icon: 'success' });
                // 刷新收藏列表
                this.fetchCollectedArticles();
              } else {
                uni.showToast({ title: response.data.msg || '取消收藏失败', icon: 'none' });
              }
            } catch (error) {
              console.error('取消收藏出错:', error);
              uni.showToast({ title: '操作失败，请重试', icon: 'none' });
            }
          }
        }
      });
    }
  }
};
</script>

<style scoped>
/* 复用主页面样式，保持一致的UI体验 */
.container {
  background-color: #fff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.navbar {
  display: flex;
  align-items: center;
  height: 44px;
  background-color: #1677ff;
  color: #fff;
  padding: 0 16px;
}

.navbar-back {
  width: 50px;
  font-size: 17px;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 17px;
  font-weight: bold;
}

.content-scroll {
  flex: 1;
  overflow-y: auto;
}

.module {
  width: 100%;
  padding: 16px;
  box-sizing: border-box;
}

.module-3 {
  margin-bottom: 20px;
}

.empty-placeholder {
  width: 100%;
  padding: 30px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
  border-radius: 12px;
  font-size: 15px;
}

.hot-articles {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.hot-title {
  font-size: 17px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 14px;
}

.articles-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.article-item {
  display: flex;
  min-height: 90px;
  cursor: pointer;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
  padding-right: 40px;
}

.article-item:last-child {
  border-bottom: none;
}

.article-img {
  width: 76px;
  height: 76px;
  border-radius: 8px;
  margin-right: 10px;
  object-fit: cover;
  flex-shrink: 0;
}

.article-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow: hidden;
}

.article-title {
  font-size: 15px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 3px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-desc {
  font-size: 13px;
  color: #909399;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.like-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  cursor: pointer;
}
</style>